<template>
  <div class="skuContent">
    <div class="title">
      <div class="title-text">{{ spectiDeatils.spectiDeatil.productName }}</div>
      <div class="price-box">
        <div class="sku-a">
          <div class="sku-a-t">{{ priceTure }}</div>
          <div class="sku-a-p">¥{{ priceShow }}</div>
        </div>
        <div class="sku-b">
          <div class="mr20">上市时间：{{ spectiDeatils.spectiDeatil.appearTime }}</div>
          <div class="mr20" v-show="spectiDeatils.spectiDeatil.isShow">已售：{{ spectiDeatils.spectiDeatil.saleNum }}</div>
          <div class="mr20">
            单位：{{
              spectiDeatils.spectiDeatil?.skuList?.length > 0
                ? useCodeArrStore().getDictName("shop_unit", spectiDeatils.spectiDeatil?.skuList[0]?.productUnit)
                : "--"
            }}
          </div>
        </div>
      </div>
    </div>
    <div class="specificate">
      <!-- 附加信息 -->
      <template v-if="spectiDeatils.spectiDeatil.productPrizeInfo">
        <p class="specificate-name">附加信息</p>
        <div class="add-info mb20 pt10 pb10 pl20 pr20">
          {{ spectiDeatils.spectiDeatil.productPrizeInfo || "-" }}
        </div>
      </template>

      <!-- 卖点 -->
      <div class="selling_point" v-if="spectiDeatils.spectiDeatil?.shopProductSellingPointDTOS?.length > 0">
        <div class="selling_point-header">卖点</div>
        <div class="selling_point-content">
          <ul
            :style="{
              justifyContent: spectiDeatils.spectiDeatil.shopProductSellingPointDTOS?.length == 3 ? 'space-between' : ''
            }"
          >
            <li
              :style="{
                width: spectiDeatils.spectiDeatil.shopProductSellingPointDTOS?.length == 3 ? '34.33%' : '31.33%',
                maxWidth: spectiDeatils.spectiDeatil.shopProductSellingPointDTOS?.length == 3 ? '34.33%' : '31.33%'
              }"
              v-for="(point_item, index) in spectiDeatils.spectiDeatil?.shopProductSellingPointDTOS"
              :key="index"
            >
              <div class="selling_point-content-header text-over" :title="point_item.subjectName">
                {{ point_item.subjectName }}
              </div>
              <div class="selling_point-content-content" v-html="point_item.content"></div>
            </li>
          </ul>
        </div>
      </div>
      <!-- 动态规格 -->
      <div class="specificate-box" v-for="(item, i) in spectiDeatils.spectiDeatil.specificationViewList" :key="i">
        <div class="specificate-name">{{ item.specificationName }}</div>
        <div class="specificate-bo">
          <div
            class="specificate-b"
            :class="{ 'disabled-wrap': itema.disable === 1 }"
            v-for="(itema, b) in item.children"
            :key="b"
          >
            <!--         sku   -->
            <div
              class="spe-box"
              :class="{ active: spectiDeatils.spectiDeatil.specificationViewList[i].showItem == b }"
              @click="addSku(item, itema, i, b, true, itema.isActive)"
            >
              <img
                class="mr10"
                v-if="itema.statsText && item.speType === specType.IMAGE_TYPE"
                :src="itema.statsText"
                alt=""
                width="24"
                height="24"
                style="border-radius: 4px"
              />

              <div
                v-if="itema.statsText && item.speType === specType.COLOR_TYPE"
                class="spe-box-img mr10"
                :style="{ 'background-color': itema.statsText }"
              ></div>
              {{ itema.propTemplateVal || itema.specificationVal }}
            </div>
            <!--         颜色   -->
            <!-- <div
              class="spe-box-img"
              :class="{ active: spectiDeatils.spectiDeatil.specificationViewList[i].showItem == b }"
              :style="{ 'background-color': itema.statsText }"
              v-if="item.speType === specType.COLOR_TYPE"
            >
              <div class="mask">
                <el-tooltip :content="itema.specificationVal" placement="bottom" effect="light">{{
                  itema.specificationVal
                }}</el-tooltip>
              </div>
            </div> -->
            <!--          图片  -->
            <!-- <div
              class="spe-box-img"
              :class="{ active: spectiDeatils.spectiDeatil.specificationViewList[i].showItem == b }"
              v-if="item.speType === specType.IMAGE_TYPE"
            >
              <img v-if="itema.statsText" :src="itema.statsText" alt="" />
              <div class="mask">
                <el-tooltip :content="itema.specificationVal" placement="bottom" effect="light">{{
                  itema.specificationVal
                }}</el-tooltip>
              </div>
            </div> -->
          </div>
        </div>
      </div>

      <div
        class="join-shop"
        v-if="spectiDeatils.spectiDeatil.productCompareList && spectiDeatils.spectiDeatil.productCompareList.length > 0"
      >
        <div class="online" @click="openDialog">线上旗舰款</div>
      </div>
    </div>

    <el-dialog
      v-model="dialogVisible"
      title="线上旗舰同款"
      modal-class="dialog"
      width="550"
      align-center
      @close="dialogVisible = false"
    >
      <div class="content">
        <div class="item" v-for="(item, index) in spectiDeatils.spectiDeatil.productCompareList" :key="item">
          <div class="item-head">
            <div class="item-text">线上同款{{ index + 1 }}</div>
            <div class="item-btn" @click="openUrl(item.url)">立即参与比价</div>
          </div>
          <div class="item-url">{{ item.url }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, onMounted, watch, ref, toRaw, nextTick } from "vue";
import { getObjKeys, getFlagArrs, _throttle } from "@/utils";
import useCodeArrStore from "@/store/modules/select";
// import ShopRemark from "./shopRemark.vue";
import { selectSpe } from "@/api/shopHome/detail";
const specType = {
  TEXT_TYPE: 1,
  COLOR_TYPE: 2,
  IMAGE_TYPE: 3
};

const textarea = ref("");
const isOpen = ref(false);
const optionInfo = ref({ skuObj: {}, remark: "" });

// setTimeout(() => {
//   textarea.value = "<p>989898</p>";
// }, 5000);
const props = defineProps({
  postData: Object
});

const onBlur = html => {
  console.log("失去焦点，请求保存接口===", html);
  optionInfo.value.remark = textarea.value;
};

const getArrayCombine = targetArr => {
  if (!Array.isArray(targetArr)) {
    return new Error("传入的参数必须是数组");
  }
  let resultArr = [];
  for (let n = 0; n <= targetArr.length; n++) {
    let flagArrs = getFlagArrs(targetArr.length, n);
    while (flagArrs.length) {
      let flagArr = flagArrs.shift();
      let combArr = Array(targetArr.length);
      for (let i = 0; i < targetArr.length; i++) {
        if (flagArr[i]) {
          combArr[i] = targetArr[i];
        }
      }
      resultArr.push(combArr);
    }
  }
  return resultArr;
};

// TODO:优化 有时间再说
const skuObjData = ref({}); // 数据集
// 暂无作用
const keys = ref([]); // 属性集
const initSKU = sku => {
  let resultSKU = [];
  let skuKeys = getObjKeys(sku);
  for (let i in skuKeys) {
    let skuKey = skuKeys[i]; // 获取一条SKU的key
    let skuData = sku[skuKey]; // 获取一条SKU的相关数据
    let skuKeyAttrs = skuKey.split(";"); // 获取SKU的key的属性数组
    let combArr = getArrayCombine(skuKeyAttrs);

    resultSKU[skuKey] = {
      count: skuData.count,
      prices: [skuData]
    };
    // for (let j = 0; j < combArr.length; j++) {
    //   let key = combArr[j].join(";");
    //   if (resultSKU[key]) {
    //     resultSKU[key].count += skuData.count;
    //     resultSKU[key].prices.push(skuData.price);
    //   } else {
    //     resultSKU[key] = {
    //       count: skuData.count,
    //       prices: [skuData]
    //     };
    //   }
    // }
  }
  return resultSKU;
};
const getSkuObj = data => {
  let skuObj = {};
  data.skuViewList?.forEach(item => {
    const properties = JSON.parse(item.properties) || [];
    const field = properties.reduce((pre, cur) => {
      return pre ? `${pre};${cur.specificationVal}` : `${pre}${cur.specificationVal}`;
    }, "");
    skuObj[field] = { ...item };
  });
  keys.value = data.specificationViewList.map(item => {
    return {
      specificationName: item.specificationName,
      item: item.children.map(item => item.specificationVal)
    };
  });
  skuObjData.value = initSKU(skuObj);
};

watch(
  () => props.postData,
  newVal => {
    console.log("这是商品详情===", newVal);
    const _newVal = JSON.parse(JSON.stringify(newVal));
    getSkuObj(_newVal);
    _newVal.specificationViewList.forEach((item, index) => {
      item.showItem = null;
      item.children?.map((_item, _index) => {
        _item.isActive = false;
      });
    });
    spectiDeatils.spectiDeatil = _newVal;
    spectiDeatils.spectiDeatil._specificationViewList = newVal.specificationViewList;

    nextTick(() => {
      spectiDeatils.spectiDeatil.specificationViewList.forEach((item, index) => {
        item.children?.map((_item, _index) => {
          if (_item.initSelect === 1) {
            addSku(item, _item, index, _index, false, _item.isActive, false);
          }
        });
      });

      // 请求接口获取置灰sku
      let activeArr = [];
      spectiDeatils.spectiDeatil.specificationViewList?.map(obj => {
        obj?.children?.map(_obj => {
          if (_obj.isActive) {
            activeArr.push({ ..._obj, specificationName: obj.specificationName });
          }
        });
      });
      selectSpeFun(activeArr);
    });

    //过滤卖点，标题和内容为空的数据过滤掉
    const arr = spectiDeatils.spectiDeatil?.shopProductSellingPointDTOS?.filter(item => {
      if ((item.content?.trim() !== "<p><br></p>" && item.content?.trim()) || item.subjectName?.trim()) {
        return item;
      }
    });
    spectiDeatils.spectiDeatil.shopProductSellingPointDTOS = arr;

    const skuItem = spectiDeatils.spectiDeatil?.skuViewList?.length ? spectiDeatils.spectiDeatil.skuViewList[0] : {};
    // console.log(90909090,spectiDeatils.spectiDeatil )
    // spectiDeatils.spectiDeatil.specificationViewList.map((item, index) => {
    //   addSku({}, index, 0);
    // });

    optionInfo.value.skuObj = skuObj.value;
    getCustomerRemarkFun(); //查询当前sku对应的备注信息
    // priceShow.value = skuItem.factoryRealPrice || 0;
    // priceTure.value = isPrice(skuItemfactoryPrice);
    // console.log('这是sku值===', spectiDeatils)
  }
);

const spectiDeatils = reactive({
  spectiDeatil: []
});
// 1文字 2颜色  3图片
const SkuLists = reactive({
  SkuList: []
});
//
const priceShow = ref("");
const priceTure = ref("正价");
//点击后查找sku
// TODO: 优化
const skuObj = ref({}); //点击之后 查找出来的sku对象
const addSku = _throttle((item, itema, a, b, getRemark, isActive, selectSpe = true) => {
  let skuItemFieldArr = [],
    skuItemField = "";
  SkuLists.SkuList = [];
  item.children?.map(obj => {
    obj.isActive = false;
  });
  itema.isActive = !isActive;
  spectiDeatils.spectiDeatil.specificationViewList[a].showItem = null;
  if (itema.isActive) {
    spectiDeatils.spectiDeatil.specificationViewList[a].showItem = b;
    spectiDeatils.spectiDeatil.specificationViewList.forEach(items => {
      skuItemFieldArr.push(items.children[items.showItem]?.specificationVal);
      SkuLists.SkuList.push(items.children[items.showItem]?.productSpecificationId);
    });
    skuItemField = skuItemFieldArr?.join(";") || "";
  }

  skuObj.value = skuObjData.value[skuItemField]?.prices[0];
  priceShow.value = skuObjData.value[skuItemField]?.prices[0]?.factoryRealPrice;
  priceTure.value = isPrice(skuObjData.value[skuItemField]?.prices[0]?.factoryPrice);
  // console.log("选中的sku===", skuObj.value);
  if (getRemark) {
    optionInfo.value.skuObj = skuObj.value;
    getCustomerRemarkFun(); //查询当前sku对应的备注信息
  }

  console.log("选中的sku===", skuObj.value);

  // 请求接口获取置灰sku
  let activeArr = [];
  spectiDeatils.spectiDeatil.specificationViewList?.map(obj => {
    obj?.children?.map(_obj => {
      if (_obj.isActive) {
        activeArr.push({ ..._obj, specificationName: obj.specificationName });
      }
    });
  });
  selectSpe && selectSpeFun(activeArr);

  /**sku匹配方案二，暂时不使用，留存备用 */
  // let propertiesArr = []
  // const _skuList = JSON.parse(JSON.stringify(spectiDeatils.spectiDeatil.skuViewList))
  // for (let skuItem of _skuList) {
  //   const arr = JSON.parse(skuItem.properties)
  //   skuItem.properties = arr
  //   propertiesArr.push(arr.map(proItem => proItem.specificationVal))
  //   skuItem.propertiesArr = propertiesArr
  //   for (let _arr of skuItem.propertiesArr) {
  //     if (arraysAreEqual(_arr, skuItemFieldArr)) {
  //       console.log('匹配上了===', _arr, skuItemFieldArr)
  //     }
  //   }
  // }
}, 0);

//查询置灰的sku规格数据
const selectSpeFun = activeArr => {
  const activeIds = activeArr?.map(item => item.specificationValId); //选中的规格ids
  const selectValArr = activeArr?.map(item => {
    return {
      specificationName: item.specificationName,
      selectVal: item.specificationVal
    };
  }); //选中的规格ids
  selectSpe({
    specificationList: spectiDeatils.spectiDeatil?._specificationViewList,
    skuList: spectiDeatils.spectiDeatil?.skuViewList,
    selectSpeList: selectValArr
  }).then(res => {
    if (res.code === 200) {
      //返回的带有disabled的规格数据
      let childArr = [];
      res.data.specificationList?.map(item => {
        childArr = [...childArr, ...item.children];
      });
      spectiDeatils.spectiDeatil?.specificationViewList?.map(item => {
        item?.children?.map(_item => {
          const currObj = childArr?.find(
            o => o.specificationValId + "=" + o.specificationVal === _item.specificationValId + "=" + _item.specificationVal
          );
          _item.disable = currObj.disable;
        });
      });
      console.log("处理后的规格===", spectiDeatils.spectiDeatil?.specificationViewList);
    }
  });
};

//查询当前sku对应的备注信息
const getCustomerRemarkFun = () => {
  // getCustomerRemark({ businessSkuId: skuObj.value.id }).then(res => {
  //   if (res.code === 200) {
  //     textarea.value = res.msg;
  //     // textarea.value = String(new Date().getTime());
  //     optionInfo.value.remark = textarea.value; //查询的备注信息传递到预算报价抽屉组件
  //   }
  // });
};

//加入购物车的话直接用 SkuLists.SkuList的数组
//监听sku变化修改价格
watch(
  () => SkuLists.SkuList,
  newVal => {
    toRaw(spectiDeatils.spectiDeatil.skuViewList).forEach((item, i) => {
      if (isArrEqual(item.skuSpecificationList, newVal)) {
        priceShow.value = item.factoryRealPrice;
        priceTure.value = isPrice(item.factoryPrice);
      }
    });
  }
);
const isPrice = factoryPrice => {
  if (factoryPrice !== null) {
    return "正价";
  } else {
    return "特价";
  }
};
const isArrEqual = (arr1, arr2) => {
  return arr1?.length === arr2?.length && arr1.every(ele => arr2.includes(ele));
};

const attributesValue = reactive({
  color: "",
  size: "",
  texture: ""
});

// 生成变体组合
// const cartesianProduct = (details) => {
//     const array = details.map(item => item.children.map(itemVal => ({ name: item.specificationName, id: item.specificationId, val: itemVal })));
//     const data = [];

//     const func = (skuarr = [], i) => {
//         for (let j = 0; j < array[i].length; j++) {
//             if (i < array.length - 1) {
//                 skuarr[i] = array[i][j] // 将当前的变体选项加入 skuarr 数组中
//                 func(skuarr, i + 1) // 递归调用下一层
//             } else {
//                 data.push([...skuarr, array[i][j]])
//             }
//         }
//         return data
//     }

//     let newList = func([], 0);

//     // 开始组装每一项变体属性
//     return newList.map(item => {
//         const attributesValue = {};

//         item.forEach(({ id, val }) => {
//             attributesValue[id] = val;
//         });
//         console.log(item);
//         return {
//             attributes: item,
//             attributesValue,
//             SKU: item.map(i => i.val),
//             stock: Math.floor(Math.random() * 6), // 生成0-5的随机整数库存
//             price: 100,
//         };
//     });
// };

// 返回当前点击选择后的对应sku对象
const getSkuObject = () => {
  return skuObj.value;
};

// 线上同款弹窗
const dialogVisible = ref(false);
const openDialog = () => {
  // 线上同款链接数>1，显示弹窗；=1，直接跳转链接，不打开弹窗
  let productCompareList = spectiDeatils.spectiDeatil.productCompareList;
  if (productCompareList.length > 1) {
    dialogVisible.value = true;
  } else {
    openUrl(productCompareList[0].url);
  }
};
const openUrl = url => {
  window.open(url, "_blank");
};

defineExpose({
  getSkuObject
});

onMounted(() => {});
</script>
<style lang="scss" scoped>
// 卖点style-begin
.selling_point {
  margin-bottom: 20px;
  &-header {
    font-size: 18px;
    color: #86909c;
  }
  &-content {
    margin-top: 10px;
    ul {
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      li {
        border-radius: 10px;
        overflow: hidden;
        margin: 0 15px 0 0;
        max-width: 31.33%;
        width: 31.33%;
        .selling_point-content-header {
          width: auto;
          height: 40px;
          background-color: #c5d3e5;
          text-align: center;
          line-height: 40px;
          font-size: 18px;
          font-weight: 700;
          color: #041830;
        }
        .selling_point-content-content {
          width: auto;
          background-color: #f5f7fa;
          padding: 20px 13px;
          overflow: hidden;
          word-wrap: break-word;
          max-height: 100px;
          overflow-y: scroll;
          font-size: 12px;
          height: 100%;
        }
      }
      li:last-child {
        margin: 0;
      }
    }
  }
}
// 卖点style-end
.skuContent {
  width: 650px;
  flex: 1;
  background-color: white;
  // max-width: 700px;
  .title {
    display: flex;
    flex-direction: column;
    padding-bottom: 20px;
    border-bottom: 1px solid #dcdfe6;

    .title-text {
      word-break: break-all;
      font-weight: 700;
      font-size: 18px;
      color: #3d3d3d;
      line-height: 32px;
      text-align: left;
      font-style: normal;
      text-transform: none;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .price-box {
      display: flex;
      margin-top: 20px;
      justify-content: space-between;

      .sku-a {
        display: flex;

        .sku-a-t {
          width: 58px;
          height: 24px;
          line-height: 24px;
          text-align: center;
          background: #ffffff;
          color: #ff8928;
          font-weight: 500;
          font-size: 16px;
          border-radius: 0;
          border: 1px solid #ff8928;
          margin-right: 20px;
        }

        .sku-a-p {
          font-weight: 700;
          font-size: 24px;
          color: #ff3333;
          line-height: 24px;
          text-align: left;
          font-style: normal;
          text-transform: none;
        }
      }

      .sku-b {
        display: flex;
        font-weight: 500;
        font-size: 12px;
        color: #86909c;
        line-height: 22px;
        text-align: center;
        font-style: normal;
        text-transform: none;
      }
    }
  }

  .join-shop {
    width: 320px;
    margin: 0 auto;
    margin-top: 20px;

    .btn {
      cursor: pointer;
      width: 320px;
      height: 50px;
      background: #1a1a1a;
      border-radius: 80px 80px 80px 80px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 500;
      font-size: 14px;
      color: rgba(255, 255, 255, 0.9);
      line-height: 22px;
      text-align: center;
      font-style: normal;
      text-transform: none;
    }
    .online {
      font-size: 14px;
      color: #ff9900;
      margin-top: 16px;
      text-align: center;
      cursor: pointer;
    }
  }

  .specificate {
    padding: 20px 0;

    .specificate-name {
      font-weight: 500;
      font-size: 18px;
      color: #86909c;
      line-height: 24px;
      margin-bottom: 10px;
      text-align: left;
      cursor: pointer;
      font-style: normal;
      text-transform: none;
    }

    .add-info {
      background-color: #f5f7fa;
      color: #3d3d3d;
      line-height: 24px;
    }

    .specificate-box {
      margin-bottom: 20px;
      display: flex;
      flex-direction: column;

      .specificate-bo {
        // display: flex;
        // flex-wrap: wrap;
        display: grid;
        gap: 20px;
        grid-template-columns: 1fr 1fr;

        .specificate-b {
          display: flex;
          flex-wrap: wrap;

          .spe-box {
            // width: 317px;
            width: 100%;
            display: flex;
            margin-bottom: 10px;
            align-items: center;
            cursor: pointer;
            justify-content: center;
            border-radius: 3px;
            border: 1px solid #dcdfe6;
            font-weight: 400;
            font-size: 14px;
            color: #606266;
            // margin-right: 20px;
            padding: 5px 10px;
            line-height: 24px;
            text-align: left;
            font-style: normal;
            text-transform: none;

            &.active {
              border: 1px solid #ff8928;
            }
          }

          &.disabled-wrap {
            cursor: not-allowed;
            .spe-box {
              pointer-events: none;
              background-color: #f9f9f9;
              color: gray;
            }
          }

          .spe-box-img {
            width: 24px;
            height: 24px;
            position: relative;

            cursor: pointer;
            border-radius: 4px;

            &.active {
              border: 1px solid #ff8928;
            }

            img {
              width: 100%;
              height: 100%;
            }

            .mask {
              display: flex;
              align-items: center;
              justify-content: center;
              position: absolute;
              bottom: 0;
              width: 90px;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 1;
              overflow: hidden;
              text-overflow: ellipsis;
              /* 解决纯字母溢出隐藏失效*/
              word-break: break-all;
              font-weight: 400;
              font-size: 14px;
              color: #ffffff;
              line-height: 24px;
              height: 24px;
              text-align: center;
              background: linear-gradient(180deg, rgba(26, 26, 26, 0.16) 0%, #1a1a1a 100%);
              border-radius: 0;

              :deep(.el-only-child__content.el-tooltip__trigger.el-tooltip__trigger) {
                display: inline-block;
                width: 100%;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                line-height: 24px;
                height: 24px;
              }
            }
          }
        }
      }
    }

    ::-webkit-scrollbar {
      width: 12px;
      /* 设置滚动条的宽度 */
    }
  }
}
.dialog {
  .content {
    margin-top: 8px;
    max-height: 360px;
    padding-right: 10px;
    overflow-y: scroll;
    .item {
      .item-head {
        display: flex;
        justify-content: space-between;
        .item-text {
          font-size: 14px;
          color: #4e5969;
        }
        .item-btn {
          font-size: 12px;
          color: #213270;
          border-bottom: 1px solid #213270;
          cursor: pointer;
        }
      }
      .item-url {
        padding: 12px 10px;
        border-radius: 2px 2px 2px 2px;
        border: 1px solid #f2f3f5;
        text-wrap: nowrap;
        overflow-x: scroll;
        margin-top: 10px;
      }
    }
    .item + .item {
      margin-top: 20px;
    }
  }
}
</style>
